package Netty.common;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.io.ByteArrayOutputStream;
import java.nio.charset.Charset;

public class Client {
    public static void main(String[] args) throws Exception {
        //客户端线程组
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            //创建客户端启动对象
            Bootstrap bootstrap = new Bootstrap();
            //设置线程组
            bootstrap.group(group)
                    // 使用NioSocketChannel作为客户端的通道实现
                    .channel(NioSocketChannel.class)
                    .handler(new Client().new MyClientChannelInitializer());
            //启动客户端去连接服务器端
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 8080).sync();
            System.out.println("Client connected");
            //对通道关闭进行监听
            channelFuture.channel().closeFuture().sync();
            System.out.println("Client closed");
        } finally {
            group.shutdownGracefully();
        }
    }

    /**
     * ChannelInitializer
     */
    class MyClientChannelInitializer extends ChannelInitializer<SocketChannel> {
        protected void initChannel(SocketChannel socketChannel) throws Exception {
            System.out.println("----- init ChannelPipeline：" + Thread.currentThread().getName());
            socketChannel.pipeline()
                    .addLast(new LineBasedFrameDecoder(1024))
//                    .addLast(new StringDecoder(Charset.forName("UTF-8"))) 会把channelRead的消息自动解析为字符串
                    .addLast(new StringEncoder(Charset.forName("UTF-8")))
                    .addLast(new MyChannelHandlerIn())
                    .addLast(new MyChannelHandlerOut());
        }
    }

    /**
     * 处理入站事间
     */
    class MyChannelHandlerIn extends ChannelInboundHandlerAdapter {
        //客户端连接服务器完成
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            System.out.println("----- channelActive：" + Thread.currentThread().getName());
            ByteBuf buf = Unpooled.copiedBuffer("小埠上线了".getBytes());
            ctx.writeAndFlush(buf);
        }
        //当通道有读取事件时会触发，即服务端发送数据给客户端
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            System.out.println("----- channelRead：" + Thread.currentThread().getName());
            ByteBuf buf = (ByteBuf) msg;
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            while (buf.readableBytes() > 0) {
                baos.write(buf.readByte());
            }
            System.out.println("收到服务端的消息:" + ctx.channel().remoteAddress() + "--> " + new String(baos.toByteArray()));
        }
        @Override
        public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
            System.out.println("----- channelReadComplete：" + Thread.currentThread().getName());
            ByteBuf buf = Unpooled.copiedBuffer("继续".getBytes());
            ctx.writeAndFlush(buf);

        }
        @Override
        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
            System.out.println("----- channelInactive：" + Thread.currentThread().getName());
            ByteBuf buf = Unpooled.copiedBuffer("小埠下线了".getBytes());
            ctx.writeAndFlush(buf);
            ctx.fireChannelInactive();
        }
        //
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            System.out.println("----- exceptionCaught：" + Thread.currentThread().getName());
            cause.printStackTrace();
            ctx.close();
        }
    }

    /**
     * 处理出站事间
     */
    class MyChannelHandlerOut extends ChannelOutboundHandlerAdapter {
        @Override
        public void read(ChannelHandlerContext ctx) throws Exception {
            System.out.println("----- read：" + Thread.currentThread().getName());
            super.read(ctx);
        }
        @Override
        public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
            System.out.println("----- write：" + Thread.currentThread().getName());
            System.out.println(msg);
            System.out.println(promise);
            ctx.write(msg, promise);
        }
    }
}
